//
//  MineViewController.m
//  陶瓷
//
//  Created by 王戈 on 15/6/10.
//  Copyright (c) 2015年 王戈. All rights reserved.
//

#import "MineViewController.h"
#import "AFNetworking.h"
#import "TCLoginView.h"
#import "MineLoginViewController.h"
#import "TCIssueViewController.h"
#import "TCMessageViewController.h"
#import "ChangeInfoView.h"
#import "TCMyMessagesViewController.h"
#import "MineLinkUsViewController.h"
#import "TCMyFavouriteController.h"
#import "ModifyPSWViewController.h"

#import <MessageUI/MessageUI.h>

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKExtension/SSEShareHelper.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKUI/SSUIShareActionSheetStyle.h>
#import <ShareSDKUI/SSUIShareActionSheetCustomItem.h>
#import <ShareSDK/ShareSDK+Base.h>


#define kDefaultNavHeight (IOS7_OR_LATER?64:44)
#define kDefaultNavTitleViewHeight 44


@interface MineViewController () <UITableViewDelegate ,UITableViewDataSource,TCLoginViewDelegate , ChangeInfoViewDelegate ,UIImagePickerControllerDelegate ,UINavigationControllerDelegate,MFMessageComposeViewControllerDelegate>

{
    NSOperationQueue *operationQueue;
    UIButton *_setButton;
    UIButton *_messageButton;
    MineLoginViewController *_mineLoginViewCV;
}
@property (nonatomic, strong) TCLoginView *loginView;
@property (nonatomic, strong) ChangeInfoView *changeView;
@property (nonatomic, strong) UIButton *cover;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation MineViewController

- (void)logoutWithSuccess
{
    self.tableView.hidden = YES;
    _messageButton.hidden = YES;
    [self changeViewStateChangeWithAppear:NO andAnimated:NO];
    [_cover removeFromSuperview];
    [self userLogin];
}

#pragma mark - lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavigationBar];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupChildView];
}

- (void)setupNavigationBar {
    
    _setButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _setButton.frame = CGRectMake(0, 0, 30,30);
        [_setButton setTitle:@"设置" forState:UIControlStateNormal];
//    [_setButton setImage:[UIImage imageNamed:@"center6"] forState:UIControlStateNormal];
    [_setButton addTarget:self action:@selector(clickSetButton:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_setButton];
    _setButton.hidden = YES;
    
    //    UIImage *messageImg = [UIImage imageNamed:@""];
    _messageButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _messageButton.frame = CGRectMake(0, 0, 30,30);
        [_messageButton setTitle:@"分享" forState:UIControlStateNormal];
//    [_messageButton setImage:[UIImage imageNamed:@"center7"] forState:UIControlStateNormal];
    [_messageButton addTarget:self action:@selector(shareDownloadURL) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_messageButton];
    
    self.navigationItem.leftBarButtonItem = leftButtonItem;
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    self.navigationController.navigationBar.translucent = NO;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationItem setTitle:@"我的账号"];
}


- (void)setupChildView {
    TCLoginView *loginView = [[[NSBundle mainBundle] loadNibNamed:@"TCLoginView" owner:nil options:nil] firstObject];
    loginView.delegate = self;
    loginView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT * 0.3);
    loginView.isLogin = NO;
    [self.view addSubview:loginView];
    self.loginView = loginView;
    
    [loginView grayBtnClickWithBlock:^(NSString *title) {
        if ([title isEqualToString:@"我的关注"]) {
            [self gotoFavourite];
        } else if ([title isEqualToString:@"已发布信息"]) {
            [self gotoMyMessage];
        }
    }];
    
    //    TCMineFirstCell *firstCell = [[[NSBundle mainBundle] loadNibNamed:@"TCMineFirstCell" owner:nil options:nil] firstObject];
    //    firstCell.frame = CGRectMake(0, CGRectGetMaxY(loginView.frame), SCREEN_WIDTH, SCREEN_HEIGHT * 0.22);
    //    [self.view addSubview:firstCell];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    //    _tableView.alpha = 0.2;
    
    [self.view addSubview:_tableView];
}

#pragma mark - Action
- (void)clickSetButton:(UIButton *)button {
    if (self.changeView) {
        [self.view addSubview:self.cover];
        [self.view addSubview:self.changeView];
        [self changeViewStateChangeWithAppear:YES andAnimated:YES];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (IsLoginIn) {
        self.loginView.isLogin = YES;
        if ([UserManager sharedUserManager].userModel.infoDict.count > 1) {
            self.loginView.infoDict = [UserManager sharedUserManager].userModel.infoDict;
        }
        else
        {
            [[TCNetworkTool sharedNetTool] getUserinfoWithSuccessBlocks:^(NSDictionary *successMessage) {
                [UserManager sharedUserManager].userModel.infoDict = successMessage;
                self.loginView.infoDict = successMessage;
            } andFailureBlocks:^(NSString *failureMessage) {
                if ([failureMessage isEqualToString:@"401"]) {
                    [self userLogin];
                }
                else
                {
                    NSLog(@"获取用户信息失败 ,请稍后重试!");
                }
            }];
        }
        _setButton.hidden = NO;
        self.tableView.hidden = NO;
        _messageButton.hidden = NO;
    } else {
        [self userLogin];
        self.tableView.hidden = YES;
        _messageButton.hidden = YES;
    }
    self.loginView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT * 0.3);
    CGFloat tabieViewY = CGRectGetMaxY(_loginView.frame) ;
    self.tableView.frame = CGRectMake(0, tabieViewY, SCREEN_WIDTH,SCREEN_HEIGHT - tabieViewY - 49 - 64);
}

- (void)clickMessageButton:(UIButton *)button {
    [self gotoMyMessage];
}

- (void)gotoMyMessage {
    [self.navigationItem setTitle:@""];
    TCMyMessagesViewController *messageVC = [[TCMyMessagesViewController alloc] init];
    [self.navigationController pushViewController:messageVC animated:YES];
}

- (void)gotoFavourite {
    [self.navigationItem setTitle:@""];
    TCMyFavouriteController *favorVC = [[TCMyFavouriteController alloc] init];
    [self.navigationController pushViewController:favorVC animated:YES];
}

- (ChangeInfoView *)changeView {
    if (_changeView == nil) {
        _changeView = [[[NSBundle mainBundle] loadNibNamed:@"ChangeInfoView" owner:nil options:nil] firstObject];
        _changeView.frame = CGRectMake(SCREEN_WIDTH * 0.5 - 150, -200, 300, 220);
        _changeView.alpha = 0;
        _changeView.infoDict = [UserManager sharedUserManager].userModel.infoDict;
        _changeView.delegate = self;
        _changeView.layer.cornerRadius = 10;
        _changeView.layer.borderColor = [UIColor blackColor].CGColor;
        _changeView.layer.borderWidth = 1;
    }
    return _changeView;
}

- (void)changeViewStateChangeWithAppear:(BOOL)appear andAnimated:(BOOL)animated {
    if (animated) {
        [UIView animateWithDuration:0.4 animations:^{
            if (appear) {
                _changeView.frame = CGRectMake(SCREEN_WIDTH * 0.5 - 150, 0, 300, 220);
                _changeView.alpha = 1;
                [_changeView.iconButton setBackgroundImage:self.loginView.iconBtn.currentBackgroundImage forState:UIControlStateNormal];
            } else {
                _changeView.frame = CGRectMake(SCREEN_WIDTH * 0.5 - 150, -200, 300, 220);
                _changeView.alpha = 0;
            }
        } completion:^(BOOL finished) {
            if (!appear) {
                [_changeView removeFromSuperview];
            }
        }];
    }
    else
    {
        if (appear) {
            _changeView.frame = CGRectMake(SCREEN_WIDTH * 0.5 - 150, 0, 300, 220);
            [_changeView.iconButton setBackgroundImage:self.loginView.iconBtn.currentBackgroundImage forState:UIControlStateNormal];
        } else {
            _changeView.frame = CGRectMake(SCREEN_WIDTH * 0.5 - 150, -200, 300, 220);
            _changeView.alpha = 0;
            [_changeView removeFromSuperview];
        }
    }
    
}

- (UIButton *)cover {
    if (_cover == nil) {
        _cover = [[UIButton alloc] initWithFrame:self.view.bounds];
        _cover.backgroundColor = [UIColor blackColor];
        _cover.alpha = 0.4;
        [_cover addTarget:self action:@selector(coverClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cover;
}

- (void)coverClick {
    if (!_changeView.isUploading) {
        [_cover removeFromSuperview];
        [self changeViewStateChangeWithAppear:NO andAnimated:YES];
    }
}

#pragma mark - change info delegate

- (void)btnResetPassword
{
    [self coverClick];
    ModifyPSWViewController *resetVC = [[ModifyPSWViewController alloc] init];
    [self.navigationController pushViewController:resetVC animated:YES];
}

// 让loginView消失的方法 , success表示上传成功后走 .failure就是直接滚蛋
- (void)disappearWithSuccess:(BOOL)success {
    [self coverClick];
    if (success) {
        self.loginView.infoDict = [UserManager sharedUserManager].userModel.infoDict;
        
        [self.loginView.iconBtn setBackgroundImage:self.changeView.iconButton.currentBackgroundImage forState:UIControlStateNormal];
        self.loginView.nameLabel.text = self.changeView.nameTextField.text;
    }
}

- (void)photoChooseWithIndex:(NSInteger)index {
    if (index) {
        [self openAlbum];
    } else {
        [self openCamera];
    }
}

/**
 *  打开照相机
 */
- (void)openCamera
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
    
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];
}
/**
 *  打开相册
 */
- (void)openAlbum
{
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
    
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    [self.changeView.iconButton setBackgroundImage:image forState:UIControlStateNormal];
}



- (void)userLogin
{
    [self.navigationItem setTitle:@""];
    _mineLoginViewCV = [[MineLoginViewController alloc] init];
    [self.navigationController pushViewController:_mineLoginViewCV animated:NO];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"TCMineCell";
    // 1.取缓存中取
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
//    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
//    }
    
    switch (indexPath.section) {
        case 0:
            if (indexPath.row == 0) {
                cell.textLabel.text = @"我的钱包";
                cell.imageView.image = [UIImage imageNamed:@"center1"];
                CGRect frame = cell.imageView.frame;
                frame.size.width /= 2;
                frame.size.height /= 2;
                cell.imageView.frame = frame;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            } else {
                UIView *middleview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDefaultWindowWidth, 50)];
                UIButton *buttonMoney = [UIButton buttonWithType:UIButtonTypeSystem];
                [buttonMoney setTitle:@"0.00\n账户余额" forState:UIControlStateNormal];
                buttonMoney.titleLabel.numberOfLines = 2;
                buttonMoney.titleLabel.textAlignment = NSTextAlignmentCenter;
                [buttonMoney setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                UIButton *buttonCost = [UIButton buttonWithType:UIButtonTypeSystem];
                [buttonCost setTitle:@"充值" forState:UIControlStateNormal];
                [buttonCost setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                buttonMoney.frame = CGRectMake(0, 10, kDefaultWindowWidth/2, 30);
                buttonCost.frame = CGRectMake(kDefaultWindowWidth/2, 10, kDefaultWindowWidth/2, 30);
                
                [middleview addSubview:buttonCost];
                [middleview addSubview:buttonMoney];
                [cell.contentView addSubview:middleview];
                cell.accessoryType = UITableViewCellAccessoryNone;
                
//                cell.textLabel.text = @"账户余额";
            }
            break;
        case 1:
            if (indexPath.row == 0) {
                cell.textLabel.text = @"发布信息";
                cell.imageView.image = [UIImage imageNamed:@"center2"];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            } else {
                cell.textLabel.text = @"信息管理";
                cell.imageView.image = [UIImage imageNamed:@"center3"];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
            break;
        case 2:
            if (indexPath.row == 0) {
                cell.textLabel.text = @"我的关注";
                cell.imageView.image = [UIImage imageNamed:@"center4"];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            } else {
                cell.textLabel.text = @"联系客服";
                cell.imageView.image = [UIImage imageNamed:@"center5"];
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }
            break;
        default:
            break;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 9;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.section) {
        case 0:
            if (indexPath.row == 0) {
                //                cell.textLabel.text = @"我的钱包";
            } else {
                //                cell.textLabel.text = @"账户余额";
            }
            break;
        case 1:
            if (indexPath.row == 0) {
                //                cell.textLabel.text = @"发布信息";
                [self.navigationItem setTitle:@""];
                TCIssueViewController *issueVC = [[TCIssueViewController alloc] init];
                [self.navigationController pushViewController:issueVC animated:YES];
            } else {
                //                TCMessageViewController *messageVC = [[TCMessageViewController alloc] init];
                [self gotoMyMessage];
            }
            break;
        case 2:
            if (indexPath.row == 0) {
                //                cell.textLabel.text = @"我的关注";
                [self gotoFavourite];
            } else {
                [self.navigationItem setTitle:@""];
                MineLinkUsViewController *mineL = [[MineLinkUsViewController alloc] init];
                mineL.titleName = @"联系客服";
                mineL.weburl = @"www.baidu.com";
                [self.navigationController pushViewController:mineL animated:YES];
                
                //                cell.textLabel.text = @"联系客服";
            }
            break;
        case 3:
            if (indexPath.row == 0) {
                [self shareDownloadURL];
            }
            break;
        default:
            nil;
            break;
    }
}

- (void)shareDownloadURL
{
    [[TCNetworkTool sharedNetTool] getShareInfoSuccessBlocks:^(NSString *successMessage) {
        [self showShareActionSheet:self.navigationController.navigationBar andMessage:successMessage];
    } andFailureBlocks:^(NSString *failureMessage) {
        [MBHUDHelper showWarningWithText:failureMessage];
    }];
    
//    if([MFMessageComposeViewController canSendText])
//    {
//        MFMessageComposeViewController *mc=[[MFMessageComposeViewController alloc] init];
//        
//        //设置委托
//        mc.messageComposeDelegate=self;
//        
//        //短信内容
//        mc.body=[[NSString alloc] initWithUTF8String:"http://www.pgyer.com/RXYT" ];
//        
//        //设置短信收件方
//        mc.recipients=[NSArray arrayWithObject:@""];
//        
//        [self presentViewController:mc animated:YES completion:nil];
//    }
}


#pragma mark 显示分享菜单

/**
 *  显示分享菜单
 *
 *  @param view 容器视图
 */
- (void)showShareActionSheet:(UIView *)view andMessage:(NSString *)message
{
    /**
     * 在简单分享中，只要设置共有分享参数即可分享到任意的社交平台
     **/
    
    //1、创建分享参数（必要）
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    NSArray* imageArray = @[];
    NSURL *url = [NSURL URLWithString:@"http://www.pgyer.com/RXYT"];
    [shareParams SSDKSetupShareParamsByText:message
                                     images:nil
                                        url:url
                                      title:nil
                                       type:SSDKContentTypeAuto];
    
    //2、分享
    [ShareSDK showShareActionSheet:view
                             items:nil
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   
                   switch (state) {
                           
                       case SSDKResponseStateBegin:
                       {
//                           [theController showLoadingView:YES];
                           break;
                       }
                       case SSDKResponseStateSuccess:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
                           if (platformType == SSDKPlatformTypeSMS && [error code] == 201)
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:@"失败原因可能是：1、短信应用没有设置帐号；2、设备不支持短信应用；3、短信应用在iOS 7以上才能发送带附件的短信。"
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           else if(platformType == SSDKPlatformTypeMail && [error code] == 201)
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:@"失败原因可能是：1、邮件应用没有设置帐号；2、设备不支持邮件应用；"
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           else
                           {
                               UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@",error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"OK"
                                                                     otherButtonTitles:nil, nil];
                               [alert show];
                               break;
                           }
                           break;
                       }
                       case SSDKResponseStateCancel:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享已取消"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       default:
                           break;
                   }
                   
                   if (state != SSDKResponseStateBegin)
                   {
//                       [theController showLoadingView:NO];
//                       [theController.tableView reloadData];
                   }
                   
               }];
}


//短信发送的处理结果
-(void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    switch (result)
    {
        case MessageComposeResultSent:
            NSLog(@"text message sent successfully");
            break;
        case MessageComposeResultCancelled:
            NSLog(@"text message cancelled");
            break;
        case MessageComposeResultFailed:
            NSLog(@"text message failed");
            break;
        default:
            NSLog(@"error happens");
            break;
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
